package com.powernode.bank.service.impl;

import com.powernode.bank.dao.AccountDao;
import com.powernode.bank.dao.impl.AccountDaoImpl;
import com.powernode.bank.exceptions.AccountNotExistException;
import com.powernode.bank.exceptions.MoneyNotEnoughException;
import com.powernode.bank.exceptions.TransferException;
import com.powernode.bank.pojo.Account;
import com.powernode.bank.service.AccountService;
import com.powernode.bank.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

public class AccountServiceImpl implements AccountService {
    AccountDao accountDao = new AccountDaoImpl();

    @Override
    public void transfer(String fromActno, String toActno, Double amount) throws AccountNotExistException, MoneyNotEnoughException, TransferException {
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        Account fromAccount = accountDao.selectByActno(fromActno);
        Account toAccount = accountDao.selectByActno(toActno);
        if (fromAccount == null || toAccount == null) {
            throw new AccountNotExistException("账户不存在");
        }
        if (fromAccount.getBalance() < amount) {
            throw new MoneyNotEnoughException("对不起，余额不足！");
        }
        fromAccount.setBalance(fromAccount.getBalance() - amount);
        toAccount.setBalance(toAccount.getBalance() + amount);
        int count = accountDao.updateByActno(fromAccount);
        count += accountDao.updateByActno(toAccount);
        if (count != 2) {
            throw new TransferException("转账失败");
        }
        sqlSession.commit();
        SqlSessionUtil.close(sqlSession);
    }
}
